package com.weblog.weblogapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.weblog.weblogapi.dao.mapper.UserMapper;
import com.weblog.weblogapi.dao.pojo.User;
import com.weblog.weblogapi.utils.JWTUtils;
import com.weblog.weblogapi.utils.SendMsg;
import com.weblog.weblogapi.utils.isValidPhoneNumber;
import com.weblog.weblogapi.vo.ErrorCode;
import com.weblog.weblogapi.vo.Result;
import com.weblog.weblogapi.vo.UserVo;
import com.weblog.weblogapi.vo.params.RegisterParam;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.weblog.weblogapi.service.UserService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import static com.weblog.weblogapi.utils.isValidPhoneNumber.isValidPhoneNumber;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    private static final String slat="dongdongblog!@#";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
    SendMsg sendMsg=new SendMsg();
    isValidPhoneNumber isValidPhoneNumber=new isValidPhoneNumber();
    @Override
    public Result sendMsg(RegisterParam registerParam) {
        String phone=registerParam.getPhone();
        if(isValidPhoneNumber.isValidPhoneNumber(phone)){
                return Result.success(sendMsg.sendMsg(phone));
        }
        return Result.fail(ErrorCode.PHONE_ERROR.getCode(),ErrorCode.PHONE_ERROR.getMsg());
    }

    @Override
    public Result register(RegisterParam registerParam) {
        String phone=registerParam.getPhone();
        String password=registerParam.getPassword();

        if(StringUtils.isBlank(password)||!isValidPhoneNumber.isValidPhoneNumber(phone)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
         if(findUserByPhone(phone)!=null){
            return Result.fail(ErrorCode.PHONE_EXIST.getCode(), ErrorCode.PHONE_EXIST.getMsg());
        }
        User user=new User();
        user.setPhone(phone);


        user.setCreateDate(sdf.format(new Date()));
        user.setPassword(DigestUtils.md5Hex(password+slat));
        user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
        user.setUsername("一只燕东");
        int i= userMapper.insert(user);
        String token = JWTUtils.createToken(user.getId());
        System.out.println(JWTUtils.checkToken(token));

        return Result.success(token);

    }
    @Override
    public Result login(RegisterParam registerParam) {
        String phone=registerParam.getPhone();
        String password=registerParam.getPassword();
        if(StringUtils.isBlank(password)||!isValidPhoneNumber.isValidPhoneNumber(phone)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        if(findUserByPhone(phone)==null){
            return Result.fail(ErrorCode.PHONE_NOT_EXIST.getCode(), ErrorCode.PHONE_NOT_EXIST.getMsg());
        }
        password=DigestUtils.md5Hex(password+slat);
        User user=findUser(phone,password);
        if(user==null){
            return Result.fail(ErrorCode.PHONE_PWD_ERROR.getCode(), ErrorCode.PHONE_PWD_ERROR.getMsg());
        }
        String token = JWTUtils.createToken(user.getId());
    /*    System.out.println(JWTUtils.checkToken(token));*/
        return Result.success(token);
    }
    @Override
    public Result msgLogin(RegisterParam registerParam) {
        String phone = registerParam.getPhone();
        if(!isValidPhoneNumber.isValidPhoneNumber(phone)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        User user=findUserByPhone(phone);
        if(findUserByPhone(phone)==null){
            User newUser = new User();
            String password = phone;
            newUser.setPhone(phone);
            newUser.setCreateDate(sdf.format(new Date()));
            newUser.setPassword(DigestUtils.md5Hex(password+slat));
            newUser.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            newUser.setUsername("一只燕东");
            int i= userMapper.insert(newUser);
            String token = JWTUtils.createToken(newUser.getId());
            return Result.success(token);
        }
        String token = JWTUtils.createToken(user.getId());
        return Result.success(token);
    }

    @Override
    public Result findPassword(RegisterParam registerParam) {
        String phone = registerParam.getPhone();
        String password = registerParam.getPassword();

        if(!isValidPhoneNumber.isValidPhoneNumber(phone)||StringUtils.isBlank(password)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        User user=findUserByPhone(phone);
        if(user==null){
             return Result.fail(ErrorCode.PHONE_NOT_EXIST.getCode(), ErrorCode.PHONE_NOT_EXIST.getMsg());
        }
        password=DigestUtils.md5Hex(password+slat);

        String userId=user.getId();
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(User::getId,userId);
        updateWrapper.set(User::getPassword,password);
        userMapper.update(null,updateWrapper);
        return Result.success("更新成功");
    }

    @Override
    public User findUserById(String id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,id);
        queryWrapper.select(User::getId,User::getUsername,User::getPhone,User::getEmail,User::getAvatar,User::getAge,User::getSex,User::getCreateDate,User::getIsMember,User::getBackDate);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);

    }

    @SneakyThrows
    @Override
    public void updateUserMember(String uid, int day) {
        LambdaUpdateWrapper<User> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        User user=findUserById(uid);
        String backDate=user.getBackDate();
        String buyDate=sdf.format(new Date());
        if(backDate==null||buyDate.compareTo(backDate)>0){
            Date sourceDate=sdf.parse(buyDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sourceDate);
            calendar.add(Calendar.DATE,+day+1);
            Date targetDate = calendar.getTime();
            backDate=sdf.format(targetDate);
            lambdaUpdateWrapper.eq(User::getId,uid);
            lambdaUpdateWrapper.set(User::getIsMember,1);
            lambdaUpdateWrapper.set(User::getBackDate,backDate);
            userMapper.update(null,lambdaUpdateWrapper);
        }else {
            Date addDate = sdf.parse(backDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(addDate);
            calendar.add(Calendar.DATE, +day + 1);
            Date targetDate = calendar.getTime();
            backDate = sdf.format(targetDate);
            lambdaUpdateWrapper.eq(User::getId,uid);
            lambdaUpdateWrapper.set(User::getIsMember,1);
            lambdaUpdateWrapper.set(User::getBackDate,backDate);
            userMapper.update(null,lambdaUpdateWrapper);
        }

    }

    @Override
    public Result updateUser(User user) {
        int i=userMapper.updateById(user);
        if(i>0){

            return Result.success(null);
        }
        return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());

    }

    @Override
    public UserVo findUserVoById(String userId) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, userId);
        queryWrapper.select(User::getUsername,User::getId,User::getAvatar);
        User user=userMapper.selectOne(queryWrapper);
        UserVo userVo=new UserVo();
        BeanUtils.copyProperties(user,userVo);

        return userVo;
    }

    @Override
    public Result findUserByToken(String token) {
        Map<String, Object> stringObjectMap=JWTUtils.checkToken(token);
        if(stringObjectMap==null){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        User user=findUserById((String) stringObjectMap.get("user"));
        if(user==null){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        return Result.success(user);
    }

    @Override
    public Result updateAvatar(User user) {
        int i=userMapper.updateById(user);
        if(i>0){

            return Result.success(null);
        }
        return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
    }

    @Override
    public User findUser(String phone, String password) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.eq(User::getPassword,password);
        queryWrapper.select(User::getId,User::getUsername,User::getPhone,User::getEmail,User::getAvatar,User::getAge,User::getSex,User::getCreateDate,User::getIsMember);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }



    @Override
    public User findUserByPhone(String phone) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.select(User::getId,User::getUsername,User::getPhone,User::getEmail,User::getAvatar,User::getAge,User::getSex,User::getCreateDate,User::getIsMember);
        queryWrapper.last("limit 1");
        User user=userMapper.selectOne(queryWrapper);
        return user;
    }


}
